//
//  PlotIncompatibilty+CRUD.m
//  PlotMate
//
//  Created by Brian Boyle on 16/04/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "PlotIncompatibilty+CRUD.h"

@implementation PlotIncompatibilty (CRUD)

+(PlotIncompatibilty *)createPlotIncompatibiltyForPlant:(Plant *)plant1 andPlant:(Plant *)plant2 inBed:(Bed *)bed withContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PlotIncompatibilty"];
    request.predicate = [NSPredicate predicateWithFormat:@"((plant1 = %@ AND plant2 = %@) OR (plant1 = %@ AND plant2 = %@)) AND bed.name = %@", plant1.name, plant2.name, plant2.name, plant1.name, bed.name];
    
    NSError *error;
    NSArray *existingIncompatibility = [context executeFetchRequest:request error:&error];
    
    if([existingIncompatibility count] == 0){
        PlotIncompatibilty *incomp = [NSEntityDescription insertNewObjectForEntityForName:@"PlotIncompatibilty" inManagedObjectContext:context];
        incomp.plant1 = plant1.name;
        incomp.plant2 = plant2.name;
        incomp.bed = bed;
        incomp.plot = bed.plot;
        incomp.alertUser = [NSNumber numberWithBool:YES];
        NSLog(@"Creating incompatibility for %@ and %@", incomp.plant1, incomp.plant2);
        return incomp;
    }
    return nil;
}

+(PlotIncompatibilty *)selectPlotIncompatibilityByPlant1Name:(NSString *)plant1Name andPlant2Name:(NSString *)plant2Name andBedName:(NSString *)bedName withContext:(NSManagedObjectContext *)context
{
     NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PlotIncompatibilty"];
    request.predicate = [NSPredicate predicateWithFormat:@"plant1 = %@ AND plant2 = %@ AND bed.name = %@", plant1Name, plant2Name, bedName];
    NSError *error;
    NSArray *incomp = [context executeFetchRequest:request error:&error];
    return [incomp lastObject];
}

@end
